package com.witframework.core.schedule;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;



/**
 * Observable代理类。用于通知观察者观测的数据发生的改变。
 * @author wuxinyang
 *
 */
public class DataChangeObservableProxy  {

	private HashMap observableList=new HashMap();

	private DataChangeObservableProxy(){}

	private static DataChangeObservableProxy instance=new DataChangeObservableProxy();
	/**
	 * 获取Observable代理类的实例
	 * @return Observable代理类实例
	 */
	public static DataChangeObservableProxy instance(){
		return instance;
	}
	/**
	 * 注册观察者
	 * @param name 观察者名称
	 * @param o 观察者实例
	 */
	public void registerObserver(String name,Observer o){
		Observable observable=(Observable)observableList.get(name);
		if(observable==null){
			observable=new DataChangeObservable();
			observableList.put(name,observable);
		}
		observable.addObserver(o);

	}
	/**
	 * 通知观察者数据已发生改变
	 * @param name 观察者名称
	 * @param arg 传递给观察者的参数
	 */
	public void notifyObservers(String name,Object arg){
		DataChangeObservable observable=(DataChangeObservable)observableList.get(name);
		if(observable!=null){
			observable.setChanged();
			observable.notifyObservers(arg);
		}
	}

	/**
	 * 通知所有观察者数据已发生改变
	 */
	public void notifyAllObervers(){
		for (Iterator iter = observableList.keySet().iterator(); iter.hasNext();) {
			String name = (String)iter.next();
			DataChangeObservable observable=(DataChangeObservable)observableList.get(name);
			if(observable!=null){
				observable.setChanged();
				observable.notifyObservers();
			}
		}
	}

	class DataChangeObservable extends Observable {
		public DataChangeObservable(){

		}
		public void setChanged(){
			super.setChanged();
		}
	}
}

